class PlayerCharacterMarker_Data {
	RadarMarker = null;
}

class PlayerCharacterMarker {
	static DataTable = [];

	static Register(player) {
		if (this.DataTable[player.ID] == null) {
			this.DataTable[player.ID] = new PlayerCharacterTag_Data();
		}
	}

	static Unregister(player) {
		//可能由于玩家OnPlayerJoin时断线，没有执行到OnPlayerComplete，因此没有Register成功
		if (this.DataTable.indexOf(player.ID) == -1) {
			return;
		}

		this.RemoveRadarMarker(player);

		if (this.DataTable[player.ID] != null) {
			this.DataTable[player.ID] = null;
		}
	}

	static UpdateAll() {
		let playerCount = World.Player.GetCount();
		for (let i = 0; i < playerCount; i++) {
			this.Update(World.Player.Get(i));
		}
	}

	static Update(player) {
		//Action
		if (player.Entity != null) {
			this.CreateRadarMarker(player);
		}
		else {
			this.RemoveRadarMarker(player);
		}
	}

	static CreateRadarMarker(player) {
		//Old
		this.RemoveRadarMarker(player);

		//New
		if (player.Entity != null) {
			let radarMarker = World.RadarMarker.Create(1, player.Entity, true, false);
			radarMarker.Scale = 0.5;
			radarMarker.Color = player.Color;
			radarMarker.Title = "Player: " + player.Name;
			radarMarker.Layer = 1; //Up

			//Ignore
			let cMatch = "-1|";
			let playerCount = World.Player.GetCount();
			for (let i = 0; i < playerCount; i++) {
				let plrID = World.Player.Get(i).ID;
				if (plrID != player.ID) {
					cMatch += `${plrID}|`;
				}
			}
			radarMarker.Match = cMatch;

			this.DataTable[player.ID].RadarMarker = radarMarker;
		}
	}

	static RemoveRadarMarker(player) {
		if (this.DataTable[player.ID].RadarMarker != null) {
			this.DataTable[player.ID].RadarMarker.Remove();
			this.DataTable[player.ID].RadarMarker = null;
		}
	}
}

World.Core.AddListener("OnScriptLoad", function () {
	Debug.Log("[PlayerCharacterMarker] by @bibiboxs");
}, -1);

World.Core.AddListener("OnPlayerComplete", function (player) {
	PlayerCharacterMarker.Register(player);
}, -1);

World.Core.AddListener("OnPlayerPart", function (player, reason) {
	PlayerCharacterMarker.Unregister(player);
}, -1);

World.Core.AddListener("OnPlayerEntityLogin", function (player, entity) {
	PlayerCharacterMarker.UpdateAll();
}, -1);

World.Core.AddListener("OnPlayerEntityLogout", function (player, entity) {
	PlayerCharacterMarker.UpdateAll();
}, -1);

World.Core.AddListener("OnPlayerColorChange", function (player, color) {
	PlayerCharacterMarker.UpdateAll();
}, -1);

World.Core.AddListener("OnPlayerNameChange", function (player, name) {
	PlayerCharacterMarker.UpdateAll();
}, -1);